package com.nantai.jiafang.nantaijiafang.nt5s.bean;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Color;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/10/23.
 */
public class DynamicLineChartManager {

    private LineChart lineChart;
    private YAxis leftAxis;
    private YAxis rightAxis;
    private XAxis xAxis;
    private LineData lineData;
    private LineDataSet lineDataSet;
    private List<ILineDataSet> lineDataSets = new ArrayList<>();
    private List<String> timeList = new ArrayList<>(); //存储x轴的时间
    private  static int num=12;            //X轴屏幕显示最大数量
    private final static float textsize=13f;    //类型标签大小
    private final static float valuetextsize=10f;    //数值标签大小
    private final static float linewidth=1.5f;    //线宽
    private final static float radio=3f;        //圆点半径
    private final static boolean radiofill=true;      //圆点是否填充
    private final static boolean fill=false;      //是否填充
    private final static boolean Circle=true;      //是圆滑曲线
    private Activity activity;

    //一条曲线
    public DynamicLineChartManager(Activity context, LineChart mLineChart, String name, int color) {
        this.lineChart = mLineChart;
        leftAxis = lineChart.getAxisLeft();
        rightAxis = lineChart.getAxisRight();
        xAxis = lineChart.getXAxis();
        activity=context;
        hengping();
        initLineChart();
        initLineDataSet(name, color);
    }

    //多条曲线
    public DynamicLineChartManager(Activity context,LineChart mLineChart, List<String> names, List<Integer> colors) {
        this.lineChart = mLineChart;
        leftAxis = lineChart.getAxisLeft();
        rightAxis = lineChart.getAxisRight();
        xAxis = lineChart.getXAxis();
        activity=context;
        hengping();
        initLineChart();
        initLineDataSet(names, colors);
    }
//横竖屏判断
    private void hengping(){
        if (activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        { // 竖屏
            num=12;
        } else {
            num=20;
        }
    }
    /**
     * 初始化LineChar
     */
    private void initLineChart() {

        lineChart.setDrawGridBackground(false);
        //显示边界
        lineChart.setDrawBorders(true);
        //隐藏左边坐标轴横网格线
        lineChart.getAxisLeft().setDrawGridLines(false);
//隐藏右边坐标轴横网格线
      //  lineChart.getAxisRight().setDrawGridLines(false);
//隐藏X轴竖网格线
        lineChart.getXAxis().setDrawGridLines(false);
        //折线图例 标签 设置
        Legend legend = lineChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(textsize);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(num);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                try {
                    String s=timeList.get((int)value);
                }catch (Exception e){
                    e.printStackTrace();
                    return "null";
                }
             //   if (value==-1)
                return timeList.get((int)value);
            }
        });

        //保证Y轴从0开始，不然会上移一点
        leftAxis.setAxisMinimum(0f);
        rightAxis.setAxisMinimum(0f);
    }

    /**
     * 初始化折线(一条线)
     *
     * @param name
     * @param color
     */
    private void initLineDataSet(String name, int color) {

        lineDataSet = new LineDataSet(null, name);
        lineDataSet.setLineWidth(linewidth);
        lineDataSet.setCircleRadius(radio);
        lineDataSet.setColor(color);
        lineDataSet.setCircleColor(color);
        lineDataSet.setHighLightColor(color);
        //设置曲线填充
        lineDataSet.setDrawFilled(fill);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(radiofill);
        lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
        lineDataSet.setValueTextSize(valuetextsize);
        if (Circle)
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        else
            lineDataSet.setMode(LineDataSet.Mode.LINEAR);
        //添加一个空的 LineData
        lineData = new LineData();
        lineChart.setData(lineData);
        lineChart.invalidate();

    }

    /**
     * 初始化折线（多条线）
     *
     * @param names
     * @param colors
     */
    private void initLineDataSet(List<String> names, List<Integer> colors) {

        for (int i = 0; i < names.size(); i++) {
            lineDataSet = new LineDataSet(null, names.get(i));
            lineDataSet.setColor(colors.get(i));

            lineDataSet.setLineWidth(linewidth);
            lineDataSet.setCircleRadius(radio);
            lineDataSet.setCircleColor(Color.RED);
            lineDataSet.setColor(colors.get(i));
            lineDataSet.setDrawFilled(fill);
            lineDataSet.setCircleColor(colors.get(i));
            lineDataSet.setHighLightColor(colors.get(i));
            if (Circle)
                lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            else
                lineDataSet.setMode(LineDataSet.Mode.LINEAR);
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
            lineDataSet.setValueTextSize(valuetextsize);
            lineDataSets.add(lineDataSet);

        }
        //添加一个空的 LineData
        lineData = new LineData();
        lineChart.setData(lineData);
        lineChart.invalidate();
    }
    //隐藏
    public void initLineDataSet(List<String> names,int[] pos) {
        for (int i = 0; i <names.size() ; i++) {
            if (pos[i]==0)
                ((LineDataSet)lineDataSets.get(i)).setVisible(false);
            else
                ((LineDataSet)lineDataSets.get(i)).setVisible(true);
        }

        lineData.notifyDataChanged();
        lineChart.notifyDataSetChanged();
        lineChart.invalidate();
    }

    /**
     * 动态添加数据（一条折线图）
     *
     * @param numbers
     */
    public void addEntry(ArrayList<String> names,ArrayList<Integer> numbers) {
        //最开始的时候才添加 lineDataSet（一个lineDataSet 代表一条线）
        if (lineDataSet.getEntryCount() == 0) {
            lineData.addDataSet(lineDataSet);
        }
        lineChart.setData(lineData);
        //避免集合数据过多，及时清空（做这样的处理，并不知道有没有用，但还是这样做了）
        /*if (timeList.size() > 11) {
            timeList.clear();
        }*/

        timeList.clear();
        for (int i = 0; i <names.size() ; i++) {
            timeList.add(names.get(i));
        }
        for (int number:
                numbers) {
            Entry entry = new Entry(lineDataSet.getEntryCount(), number);
            lineData.addEntry(entry, 0);
        }

        //通知数据已经改变
        lineData.notifyDataChanged();
        lineChart.notifyDataSetChanged();
        //设置在曲线图中显示的最大数量
        lineChart.setVisibleXRangeMaximum(num);
        //移到某个位置
        lineChart.moveViewToX(lineData.getEntryCount() - 5);
    }
    /**
     * 动态添加数据（多条折线图）
     *
     * @param numbers
     */
    public void addEntry(ArrayList<String> names,List<ArrayList<Float>> numbers) {
        if (lineDataSets.get(0).getEntryCount() == 0) {
            lineData = new LineData(lineDataSets);
            lineChart.setData(lineData);
        }
     /*  if (timeList.size() > 11) {
            timeList.clear();
        }*/
        timeList.clear();
       for (int i = 0; i <names.size() ; i++) {
            timeList.add(names.get(i));
        }
        for (int i = 0; i < numbers.get(0).size(); i++) {
            for (int j = 0; j < numbers.size(); j++) {
                Entry entry = new Entry(lineDataSet.getEntryCount(), numbers.get(j).get(i));
                lineData.addEntry(entry, j);
                lineData.notifyDataChanged();
                lineChart.notifyDataSetChanged();
                // 设置在曲线图中显示的最大数量
                lineChart.setVisibleXRangeMaximum(num);
                lineChart.moveViewToX(lineData.getEntryCount() - 5);
            }
        }
    }

    /**
     * 设置Y轴值
     *
     * @param max
     * @param min
     * @param labelCount
     */
    public void setYAxis(float max, float min, int labelCount) {
        if (max < min) {
            return;
        }
        leftAxis.setAxisMaximum(max);
        leftAxis.setAxisMinimum(min);
        leftAxis.setLabelCount(labelCount, false);

        rightAxis.setAxisMaximum(max);
        rightAxis.setAxisMinimum(min);
        rightAxis.setLabelCount(labelCount, false);
        lineChart.invalidate();
    }

    /**
     * 设置高限制线
     *
     * @param high
     * @param name
     */
    public void setHightLimitLine(float high, String name, int color) {
        if (name == null) {
            name = "高限制线";
        }
        LimitLine hightLimit = new LimitLine(high, name);
        hightLimit.setLineWidth(4f);
        hightLimit.setTextSize(10f);
        hightLimit.setLineColor(color);
        hightLimit.setTextColor(color);
        leftAxis.addLimitLine(hightLimit);
        lineChart.invalidate();
    }

    /**
     * 设置低限制线
     *
     * @param low
     * @param name
     */
    public void setLowLimitLine(int low, String name) {
        if (name == null) {
            name = "低限制线";
        }
        LimitLine hightLimit = new LimitLine(low, name);
        hightLimit.setLineWidth(4f);
        hightLimit.setTextSize(10f);
        leftAxis.addLimitLine(hightLimit);
        lineChart.invalidate();
    }

    /**
     * 设置描述信息
     *
     * @param str
     */
    public void setDescription(String str) {
        Description description = new Description();
        description.setText(str);
        lineChart.setDescription(description);
        lineChart.invalidate();
    }
}
